
package com.benimetum.beans;

import com.benimetum.items.Answer;
import com.benimetum.items.Course;
import com.benimetum.items.Homework;
import com.benimetum.managers.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.MimetypesFileTypeMap;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Ethem Cem Ozkan
 * @email ethemcem.ozkan@gmail.com
 * No 07110604
 */
@ManagedBean(name="HomeworkBean")
@SessionScoped
public class HomeworkBean
{
    private Homework target;
    private Answer targetAnswer;
    private File targetFile;
    private int score;
    private boolean error;
    private String message;
    private Date date;
    private String hwİnfo;
    private String fileInfo;
    private ArrayList<UploadedFile> file;
    private Course course;
    private String courseId;

    public HomeworkBean() {
        file=new ArrayList<UploadedFile>();
    }

    
    public Answer getTargetAnswer() {
	  return targetAnswer;
    }

    public Course getCourse() {
	  return course;
    }

    public Date getDate() {
	  return date;
    }

    public String getCourseId() {
	  return courseId;
    }

    public File getTargetFile() {
	  return targetFile;
    }

    public ArrayList<UploadedFile> getFile() {
	  return file;
    }

    public String getFileInfo() {
	  return fileInfo;
    }

    public String getHwİnfo() {
	  return hwİnfo;
    }
    
    public int getScore() {
	  return score;
    }
    
    public Homework getTarget() {
	  return target;
    }

    public boolean getError() {
	  return error;
    }
    
    public String getMessage() {
	  return message;
    }

    public void setTarget(Homework target) {
	  this.target = target;
    }

    public void setScore(int score) {
	  this.score = score;
    }

    public void setMessage(String message) {
	  this.message = message;
    }

    public void setError(boolean error) {
	  this.error = error;
    }

    public void setCourseId(String courseId) {
	  this.courseId = courseId;
    }

    public void setTargetFile(File targetFile) {
	this.targetFile = targetFile;
    }

    public void setHwİnfo(String hwİnfo) {
	  this.hwİnfo = hwİnfo;
    }

    public void setFileInfo(String fileInfo) {
	  this.fileInfo = fileInfo;
    }

    public void setFile(ArrayList<UploadedFile> file) {
	  this.file = file;
    }

    public void setDate(Date date) {
	  this.date = date;
    }

    public void setCourse(Course course) {
	  this.course = course;
    }

    public void setTargetAnswer(Answer targetAnswer) {
	  this.targetAnswer = targetAnswer;
    }
    
    public Answer[] getAnswers(){
	  return HomeworkManager.getHomeworksAnswer(target.getId());
    }
    
    public void giveScore(){
	  error=HomeworkManager.checkAnswer(targetAnswer.getId(), score, LoginManager.getUser().getId());
	  if(error=false)
		message="Hata oluştu.";
	  else
		message="Başarıyla puanlandırıldı.";
			 
    }
    
    public void addHomework(){
	  File f=FileManager.convertUploadedFileToFile(file.get(0));
	  error=HomeworkManager.createHomework(courseId, f, fileInfo, hwİnfo, date);
	  AnnouncementManager.createCourseEvent("[ODEV]["+courseId.replace("c","") +"]"+hwİnfo, date, CourseManager.getCoursesStudents(courseId), CourseManager.getCoursesTeacher(courseId).getId(), courseId);
	  try {
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	  } catch (IOException ex) {
		Logger.getLogger(HomeworkBean.class.getName()).log(Level.SEVERE, null, ex);
	  }
    }
    
    public boolean answersSender(){
	  return targetAnswer.getStudent().getId().equals(LoginManager.getUser().getId());
    }
    
    public Course[] teacherCourse(){
	  return TeacherManager.getTeachersCourses(LoginManager.getUser().getId());
    }
    
    public void addAnswer(){
	  File[] f=new File[file.size()];
          String[] s=new String[file.size()];
          for (int i = 0; i < f.length; i++) {
            f[i]=FileManager.convertUploadedFileToFile(file.get(i));
            s[i]=fileInfo;
        }
	  
	  HomeworkManager.addAnswer(target.getId(), f, s, LoginManager.getUser().getId());
    }
    
    public StreamedContent convert(){
	  String path = targetFile.getPath();
	  String canonicalFile;
		canonicalFile = targetFile.getAbsolutePath();
	  InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/"+targetFile.getPath());  
        return new DefaultStreamedContent(stream, new MimetypesFileTypeMap().getContentType(targetFile), targetFile.getName());  
    }
    
    public boolean answersTeacher(){
	  return target.getCourse().getTEACHER().getId().equals(LoginManager.getUser().getId());
    }
    
    public boolean checkAnswer(){
        return targetAnswer!=null;
    }
    
    public boolean checkHomework(){
        return target!=null;
    }
    
    public Answer[] getStudentAnswer(){
        return HomeworkManager.getStudentsAnswers(LoginManager.getUser().getId());
    }
    
    public boolean sent(){
        return HomeworkManager.isSent(LoginManager.getUser().getId(), target.getId());
    }
    
    public void uploadListener(FileUploadEvent event) {  
        file.add(event.getFile());
        FacesMessage msg = new FacesMessage("Yüklendi", event.getFile().getFileName() + " adlı dosya yüklendi.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
}
